import React, { Component, createContext } from 'react';
import './index.css'

// 创建Context对象
const MyContext = React.createContext()
// 解构赋值取Provider, Consumer
const { Provider, Consumer } = MyContext

class A extends Component {
    state = { username: 'tom', age: 11 }

    render() {
        const { username, age } = this.state
        return (
            <div className='parent'>
                <h2>I am A</h2>
                <h4>My username is {username}</h4>
                <Provider value={{ username, age }}>
                    <B name='lili' />
                </Provider>
            </div>
        );
    }
}
class B extends Component {
    render() {
        return (
            <div className='child'>
                <h2>I am B</h2>
                <h4>My username is {this.props.name}</h4>
                <C />
                <D />
            </div>
        );
    }
}
class C extends Component {
    // 声明接收context
    static contextType = MyContext
    render() {
        return (
            <div className='grand'>
                <h2>I am C</h2>
                <h4>My username is {this.context.username}</h4>
            </div>
        );
    }
}
function D() {
    return (
        <div className='grand' style={{ backgroundColor: 'antiquewhite' }}>
            <h2>I am D</h2>
            <h4>My username is
                <Consumer>
                    {
                        value => {
                            return ` ${value.username}`
                        }
                    }
                </Consumer>
            </h4>
        </div>
    );
}
class Demo extends Component {
    render() {
        return (
            <div>
                <A />
            </div>
        );
    }
}

export default Demo;